<?php
namespace app\service;
use think\facade\Db;
use app\model\StockModel;
use Exception;

class StockService{  
    public function list($params){
        $where=[];
        $page = $params['page'];
        $pageCount = $params['page_count'];

        //按出发日期查询
        if(!empty($params['start_date']) && !empty($params['end_date'])){
            if(!empty($params['start_date'])){
                $where[] = ['a.start_date','>= time',$params['start_date']];  
            }
            if(!empty($params['end_date'])){
                $where[] = ['a.start_date','<= time',$params['end_date']];  
            }
        } 
        
        if(!empty($params['keyword'])){
            $where[] = ['a.product_name|a.product_no|a.payment_no|a.sn','like',"%{$params['keyword']}%"];   
        }
        if(!empty($params['payment_no'])){
            $where[] = ['a.payment_no','=',$params['payment_no']];  
        }
        if(!empty($params['sn'])){
            $where[] = ['a.sn','=',$params['sn']];  
        }
        if(!empty($params['stock_id'])){
            $where[] = ['a.stock_id','=',$params['stock_id']];  
        }       
        if(!empty($params['category_id'])){
            $where[] = ['a.category_id','=',$params['category_id']];  
        }
        if(!empty($params['operator_id'])){
            $where[] = ['a.operator_id','=',$params['operator_id']];  
        }
        if(!empty($params['stat'])){
            $where[] = ['a.stat','=',1];  
        }else{
            $where[] = ['a.stat','=',0]; 
        }
        
        
        $data = StockModel::alias('a')
            ->field('a.*,b.cn_name as operator,c.name as category,d.title as warehouses,e.supplier_id,e.model,e.unit_id')           
            ->join('user b','a.operator_id=b.id','left')
            ->join('product_type c','a.category_id=c.id','left')  
            ->join('category d','a.warehouses_id=d.id','left') 
            ->join('buy e','a.buy_id=e.id','left') 
            ->where($where)->page($page,$pageCount)->order('id','desc')->select();
        foreach ($data as &$v) {
            $stock = Db::name('stock')->where(['sid'=>$v['id']])->sum('num'); 
            $v['stock'] = $v['num']-$stock;  
            $v['supplier_name'] = Db::name('supplier')->where(['id'=>$v['supplier_id']])->value('supplier_name'); 
            $v['unit'] = Db::name('category')->where(['id'=>$v['unit_id']])->value('title'); 
        }
        $count = StockModel::alias('a')->where($where)->count(); 
        return ["list"=>$data,"count"=>$count];
    } 

    public function now($params){
        $where=[];
        $page = $params['page'];
        $pageCount = $params['page_count'];

        //按出发日期查询
        if(!empty($params['start_date']) && !empty($params['end_date'])){
            if(!empty($params['start_date'])){
                $where[] = ['a.start_date','>= time',$params['start_date']];  
            }
            if(!empty($params['end_date'])){
                $where[] = ['a.start_date','<= time',$params['end_date']];  
            }
        } 
        
        if(!empty($params['keyword'])){
            $where[] = ['a.product_name|a.product_no|a.payment_no|a.sn','like',"%{$params['keyword']}%"];   
        }
        if(!empty($params['payment_no'])){
            $where[] = ['a.payment_no','=',$params['payment_no']];  
        }
        if(!empty($params['sn'])){
            $where[] = ['a.sn','=',$params['sn']];  
        }
        if(!empty($params['stock_id'])){
            $where[] = ['a.stock_id','=',$params['stock_id']];  
        }       
        if(!empty($params['category_id'])){
            $where[] = ['a.category_id','=',$params['category_id']];  
        }
        if(!empty($params['operator_id'])){
            $where[] = ['a.operator_id','=',$params['operator_id']];  
        }
        if(!empty($params['stat'])){
            $where[] = ['a.stat','=',1];  
        }else{
            $where[] = ['a.stat','=',0]; 
        }
        
        
        $data = StockModel::alias('a')
            ->field('a.*,b.cn_name as operator,c.name as category,d.title as warehouses,e.model')           
            ->join('user b','a.operator_id=b.id','left')
            ->join('product_type c','a.category_id=c.id','left')  
            ->join('category d','a.warehouses_id=d.id','left') 
            ->join('buy e','a.buy_id=e.id','left') 
            ->where($where)->page($page,$pageCount)->order('id','desc')->select();
        foreach ($data as &$v) {
            $stock = Db::name('stock')->where(['sid'=>$v['id']])->sum('num'); 
            $v['out_stock'] = $stock;  
            $v['now_stock'] = $v['num']-$stock;  
            
        }
        $count = StockModel::alias('a')->where($where)->count(); 
        return ["list"=>$data,"count"=>$count];
    }

    public function getByPaymentNo($params){
        $where=[];      
        $where[] = ['a.payment_no','=',$params['payment_no']];  
        $where[] = ['a.stat','=',0];  
        
        
        $data = StockModel::alias('a')
            ->field('a.*,b.cn_name as operator,c.name as category,d.title as warehouses')           
            ->join('user b','a.operator_id=b.id','left')
            ->join('product_type c','a.category_id=c.id','left')  
            ->join('category d','a.warehouses_id=d.id','left') 
            ->where($where)->order('id','desc')->select();
        foreach ($data as &$v) {
            $stock = Db::name('stock')->where(['sid'=>$v['id']])->sum('num'); 
            $v['stock'] = $v['num']-$stock;  
        }
       
        return $data;
    } 
    
    public function info($id){
        $stocks = StockModel::alias('a')
            ->field('a.*,b.cn_name as operator,c.name as category')           
            ->join('user b','a.operator_id=b.id','left')
            ->join('product_type c','a.category_id=c.id','left')  
            ->where('id',$id)->find(); 
        $stocks['buyInfo'] = Db::name('buy')->where(['type'=>$stocks['type'],'buy_id'=>$stocks['buy_id']])->select();         
        return $stocks;
    }
    

    public function save($params){              
        if(empty($params['id'])){ 
            $datas = [];  
            foreach ($params['datas'] as $v) {
                $datas[] = [
                    "type" => $v['type'],
                    "buy_id"=>$v['id'],
                    "start_date"=>$params['warehousing_date'],
                    "num"=>$v['stocknum'],
                    "payment_no"=>$v['payment_no'],
                    "warehouses_id"=>$v['stock'],
                    "product_no"=>$v['product_no'],
                    "cost_price"=>$v['cost_price'],
                    "category_id"=>$v['category_id'],
                    "product_name" =>$v['content'],
                    "sn" =>"RK-" . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                    "operator_id"=>$params['operator_id'],
                    "remark"=>$params['remark'],
                    "create_time"=>time(),
                    "update_time"=>time()
                ];
            }
            $data = StockModel::insertAll($datas); 
        }else{
            $data = StockModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function out_save($params){              
        if(empty($params['id'])){ 
            
            $datas = [];  
            foreach ($params['datas'] as $v) {
                $stock = Db::name('stock')->where(['id'=>$v['id']])->find();  
                $datas[] = [
                    "type" => $stock['type'],
                    "sid"=>$v['id'],
                    "start_date"=>$params['warehousing_date'],
                    "num"=>$v['stocknum'],
                    "payment_no"=>$stock['payment_no'],
                    "warehouses_id"=>$stock['warehouses_id'],
                    "product_no"=>$stock['product_no'],
                    "cost_price"=>$stock['cost_price'],
                    "category_id"=>$stock['category_id'],
                    "product_name" =>$stock['product_name'],
                    "sn" =>"CK-" . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                    "operator_id"=>$params['operator_id'],
                    "remark"=>$params['remark'],
                    "stat"=>1,    
                    "delivery_no"=>$params['delivery_no'],       
                    "create_time"=>time(),
                    "update_time"=>time()
                ];
            }
            $data = StockModel::insertAll($datas);         
        }else{
            $data = StockModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = StockModel::destroy($params['id']);         
        return $data;
    }

    public function csv($params){
        $where=[];        
        //按出发日期查询
        if(!empty($params['start_date']) && !empty($params['end_date'])){
            if(!empty($params['start_date'])){
                $where[] = ['a.start_date','>= time',$params['start_date']];  
            }
            if(!empty($params['end_date'])){
                $where[] = ['a.start_date','<= time',$params['end_date']];  
            }
        } 
        if(!empty($params['keyword'])){
            $where[] = ['a.content|a.payment_no|a.sn','like',"%{$params['keyword']}%"];   
        }
        if(!empty($params['payment_no'])){
            $where[] = ['a.payment_no','=',$params['payment_no']];  
        }
        if(!empty($params['sn'])){
            $where[] = ['a.sn','=',$params['sn']];  
        }
        if(!empty($params['stock_id'])){
            $where[] = ['a.stock_id','=',$params['stock_id']];  
        }       
        if(!empty($params['category_id'])){
            $where[] = ['a.category_id','=',$params['category_id']];  
        }
        if(!empty($params['operator_id'])){
            $where[] = ['a.operator_id','=',$params['operator_id']];  
        }
        if(!empty($params['stat'])){
            $where[] = ['a.stat','=',1];  
        }else{
            $where[] = ['a.stat','=',0]; 
        }

        $data = StockModel::alias('a')
            ->field('a.*,b.cn_name as operator,c.name as category')           
            ->join('user b','a.operator_id=b.id','left')
            ->join('product_type c','a.category_id=c.id','left')     
            ->where($where)->order('id','desc')->select();
        foreach ($data as &$v) {
            $v['total_price'] = $v['cost_price'] * $v['num'];
        }
        return $data;
    } 
}